package com.tengju.data.infrastructure.schedule;

import com.tengju.data.application.profit.MarketBonusService;
import com.tengju.data.domain.model.alert.AlertEvent;
import com.tengju.data.domain.model.alert.AlertService;
import com.tengju.data.domain.model.report.AchievementBonusLogRepository;
import com.tengju.data.domain.model.report.AchievementBonusRepository;
import com.tengju.data.infrastructure.exception.ScheduleJobException;
import com.tengju.data.infrastructure.persistence.redis.RedisLock;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
@Slf4j
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class MarketBonusMidTableClearJob {

    private final MarketBonusService marketBonusService;
    private final AlertService alertService;
    private final RedisLock redisLock;

    private String JOB_NAME = "市场补贴中间记录定期清理任务";

    private final String JOB_KEY = "marketProfitMidTableClearJob";

    @XxlJob("marketProfitMidTableClearJob")
    public ReturnT<String> execute(String params) {
        String lockToken = null;
        try {
            lockToken = redisLock.tryLock(JOB_KEY, 1000 * 60 * 60);
            if (StringUtils.isBlank(lockToken)) {
                throw new ScheduleJobException("任务正在执行中,稍后再试");
            }
            LocalDateTime today = LocalDateTime.now();
            LocalDateTime clearDate = today.minusDays(8);
            marketBonusService.clearMarketProfitMidTable(clearDate);
        } catch (Exception e) {
            log.error("{}, jobError",JOB_NAME, e);
            AlertEvent event = new AlertEvent(JOB_NAME + "异常");
            event.addItem("任务参数",params);
            event.addItem("异常信息",e.getMessage());
            alertService.alert(event);
            return ReturnT.FAIL;
        } finally {
            redisLock.unlock(JOB_KEY,lockToken);
        }
        return ReturnT.SUCCESS;
    }

}
